//
//  ViewController.swift
//  TBCode
//
//  Created by nexgo on 2017/9/29.
//  Copyright © 2017年 truth. All rights reserved.
//

import UIKit
import SVPullToRefresh

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var listView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initView();
        
        initBLE();
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 初始化控件
    private func initView(){
        listView.dataSource = self;
        listView.delegate = self;
        listView.addPullToRefresh(actionHandler: self.restartScan);
    }
    
    private func restartScan(){
        
        bleManager.stopScan();
        
        devices.removeAll();
        listView.reloadData();
        
        self.perform(#selector(startScan), with: nil, afterDelay: 1);
    }
    
    // 初始化蓝牙
    private var bleManager:TBBLEManager!;
    private var scanCB:TBBLEScanCB!;
    private func initBLE(){
        scanCB = TBBLEScanCB();
        scanCB.onScan = self.onScan;
        scanCB.onScanFail = self.onScanFail;
        scanCB.onScanOver = self.onScanOver;
        
        let nc = NotificationCenter.default;
        nc.addObserver(self, selector:#selector(self.bleEnableChange), name: NSNotification.Name(rawValue: TBBLE_STATUSCHANGED), object: nil);
        
        bleManager = TBBLEManager.getInstance();
    }

    @objc func bleEnableChange(notification:NSNotification){
        let enable = notification.object as! Bool;
        
        if(enable){
            print("开始扫描");
            startScan();
        }
    }

    @objc func startScan(){
        listView.pullToRefreshView.stopAnimating();
        bleManager.startScan(TBBLE_FAST, serviceUuids: nil, scanCB: scanCB, workTime: 30, sleepTime: 1, workTimes: 1);
    }
    
    // ****************************蓝牙扫描回调
    private func onScan(device: TBBLEDevice){
//        print("onScan->\(device.peripheral.name)");
        
        for deviceTmp in devices {
            if(deviceTmp.peripheral.identifier.uuidString == device.peripheral.identifier.uuidString){
                deviceTmp.refreshInfo(device);
                listView.reloadData();
                return;
            }
        }
        
        devices.append(device);
        
        listView.reloadData();
    }
    
    private func onScanFail(errorCode: TBErrorCode){
        print("onScanFail->\(errorCode.msg)");
    }
    private func onScanOver(){
        print("onScanOver");
    }
    
    // ****************************列表回调
    private var devices:[TBBLEDevice] = [TBBLEDevice]();
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return devices.count;
    }
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let obj: AnyObject? = tableView.dequeueReusableCell(withIdentifier: "DeviceCell");
        var cell: DeviceCell!;
        if(obj == nil){
            cell = DeviceCell.getNewCell();
        }else{
            cell = obj as! DeviceCell;
        }
        
        cell.setData(device: devices[indexPath.row])
        
        return cell;
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 64;
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true);
        
        let selectedDevice = devices[indexPath.row];
        
        let vc = ComViewController.getActivity();
        vc.workDevice = selectedDevice;
        
        self.present(vc, animated: false, completion: {
            
        });
        
    }
    
}

